<!-- 聊天页面 - 使用封装的组件 -->
<template>
  <view class="chat-page">
    <!-- 自定义导航栏 -->
    <tn-nav-bar
      fixed
      alpha
      backgroundColor="#020303"
      :isBack="true"
      fontColor="#FFFFFF"
      @leftClick="goBack">
      <view class="nav-title">
        <text class="user-status-dot" :class="{'online': otherUser.onlineStatus}"></text>
		<text class="user-nickname">{{otherUser.name}}</text>
      </view>
      <view slot="right" @tap="showChatOptions" :style="{top: vuex_status_bar_height + 4 + 'px'}" class="nav-right-button">
        <text class="tn-icon-more-circle nav-right-icon neon-icon"></text>
      </view>
    </tn-nav-bar>

    <!-- 页面内容区域，添加一个顶部安全距离 -->
    <view class="chat-content" :style="{ paddingTop: '90rpx' }">
      <chat-container
        ref="chatContainer"
        :target-id="otherUser.id"
        :emoji-list="emojiList"
        :is-target-online="otherUser.onlineStatus"
        :can-add-wechat="otherUser.canAddWechat"
        :is-vip="userInfo.isVip"
        @query-messages="handleQueryMessages"
        @send-text="handleSendText"
        @tool-click="handleToolClick"
        @recall-message="handleRecallMessage"
        @delete-message="handleDeleteMessage"
        @resend-message="handleResendMessage"
        @keyboard-height-change="handleKeyboardHeightChange"
        @keyboard-hide="handleKeyboardHide"
        @add-wechat="handleAddWeChat"
        @complete-wechat="handleCompleteWeChat"
        @view-wechat="handleViewWeChat"
        @show-vip-modal="handleShowVipModal"
      >
        <template #top>
          <view :style="{height: vuex_status_bar_height + 44 + 'px'}"></view>

          <!-- 用户资料卡片 -->
          <view class="user-profile-card" :class="{'vip-card': otherUser.vip}">
            <!-- 背景气泡特效（普通用户） -->
            <view class="bubble-container" v-if="!otherUser.vip">
              <view class="bubble bubble-1"></view>
              <view class="bubble bubble-2"></view>
              <view class="bubble bubble-3"></view>
              <view class="bubble bubble-4"></view>
              <view class="bubble bubble-5"></view>
              <view class="bubble bubble-6"></view>
            </view>

            <!-- VIP金色粒子特效 -->
            <view class="vip-effects" v-if="otherUser.vip">
              <view class="gold-particle particle-1"></view>
              <view class="gold-particle particle-2"></view>
              <view class="gold-particle particle-3"></view>
              <view class="gold-particle particle-4"></view>
              <view class="gold-particle particle-5"></view>
              <view class="gold-particle particle-6"></view>
              <view class="gold-particle particle-7"></view>
              <view class="gold-particle particle-8"></view>
              <view class="gold-particle particle-9"></view>
              <view class="gold-particle particle-10"></view>
              <view class="gold-particle particle-11"></view>
              <view class="gold-particle particle-12"></view>
              <view class="vip-glow"></view>
            </view>

            <view class="card-main">
              <!-- 左侧用户头像和基本信息 -->
              <view class="user-basic-info">
                <image class="user-avatar" :src="otherUser.avatar || 'https://rbtnet.oss-cn-hangzhou.aliyuncs.com/f58cad729ce47acb65666e57496f5e2e0c8badfec8355cfc7d6f2645f8738e60.jpeg'" mode="aspectFill"></image>
                <view class="user-name-info">
                  <view class="user-name-wrapper">
                    <text class="user-nickname">{{otherUser.name}}</text>
                    <image v-if="otherUser.vip" src="/static/images/vip-icon.png" class="vip-icon" mode="aspectFit"></image>
                  </view>
                  <view class="user-tags">
                    <text class="tag age">{{otherUser.age < 18 ? 18 : otherUser.age}}岁</text>
                    <text class="tag gender">{{otherUser.gender}}</text>
                    <text class="tag location">{{otherUser.city || '未知'}}</text>
                  </view>
                  <view class="user-signature" v-if="otherUser.signature">{{otherUser.signature}}</view>
                </view>
              </view>

              <!-- 右侧照片预览 -->
              <view class="user-albums-preview" v-if="otherUser.albums && otherUser.albums.length > 0">
                <image
                  v-for="(album, index) in otherUser.albums.slice(0, 3)"
                  :key="index"
                  :src="album.imageUrl"
                  class="album-preview-image"
                  mode="aspectFill"
                  @tap="previewImage(album.imageUrl)"
                ></image>
                <view class="album-more" v-if="otherUser.albums.length > 3" @tap="previewImage(otherUser.albums[0].imageUrl)">
                  <text>+{{otherUser.albums.length - 3}}</text>
                </view>
              </view>
            </view>

            <!-- 兴趣标签区域 - 单行横向滚动 -->
            <scroll-view class="interest-scroll" scroll-x="true" show-scrollbar="false" v-if="otherUser.interestTags && otherUser.interestTags.length > 0">
              <view class="interest-tags">
                <text
                  v-for="(tag, index) in otherUser.interestTags"
                  :key="index"
                  class="interest-tag"
                  :class="{'vip-tag': otherUser.vip}"
                >{{tag.name}}</text>
              </view>
            </scroll-view>

            <!-- 操作按钮区域 -->
            <view class="action-buttons">
              <!-- 添加微信按钮 -->
              <view class="wechat-button-in-card" @tap="handleAddWeChat(otherUser.id)" v-if="!wxAuditMode">
                <image src="/static/images/wechat.png" class="wechat-icon-small"></image>
                <text class="wechat-text">添加微信</text>
              </view>
              
              <!-- 举报用户按钮 -->
              <view class="report-button-in-card" @tap="handleReportUser">
                <text class="report-icon">⚠️</text>
                <text class="report-text">举报用户</text>
              </view>
            </view>
          </view>
        </template>
      </chat-container>


    </view>

    <!-- 添加订阅消息组件 -->
    <ChatSubscribe
      :show.sync="showSubscribe"
      :sender-name="otherUser.name"
      :last-message="lastMessageContent"
      @success="onSubscribeComplete"
    />

	<!-- 添加VIP弹窗组件 -->
	<vip-popup
	  :show.sync="isVipModalVisible"
	  :userInfo="userInfo"
	  @purchase-success="onVipPurchaseSuccess"
	></vip-popup>

    <!-- 添加举报弹窗组件 -->
    <report-popup
      v-model="showReportPopup"
      :reportData="reportData"
      @submit="handleReportSubmit"
      @cancel="handleReportCancel"
    ></report-popup>
  </view>
</template>

<script>
import ChatContainer from '@/components/chat/ChatContainer.vue';
import { getUserById, getUserWechat, approveWechatRequest } from '@/api/user/index.js';
// 导入IM相关API
import {
  getMessagePage,
  sendMessage,
  readMessage,
  recallMessage,
  deleteMessage,
  deleteAllMessages
} from '@/api/im/message.js';
// 导入文件上传API
import { uploadFile } from '@/api/upload/index.js';
// 导入订阅相关工具
import ChatSubscribe from '@/components/subscribe/chat/index.vue'; // 导入订阅消息组件
import VipPopup from '@/components/vip/vip-popup.vue';
import SubscribeManager, { STORAGE_KEYS } from '@/utils/subscribe-manager.js'; // 导入订阅管理工具类
import { MESSAGE_COUNTER_THRESHOLD } from '@/utils/constants/subscribe-config.js'; // 导入消息计数器阈值配置
import { mapGetters, mapActions } from 'vuex';
import ReportPopup from '@/components/common/ReportPopup.vue';
// 导入API统一入口
import api from '@/api/index.js';
// 导入视频通话相关API
import { initiateCall } from '@/api/im/videocall.js';
// 导入 URLSearchParams polyfill（兼容微信小程序）
import { getURLSearchParams } from '@/utils/url-search-params-polyfill.js';

export default {
  components: {
    ChatContainer,
    ChatSubscribe, // 注册订阅消息组件
	VipPopup,
    ReportPopup
  },
  data() {
    return {
      otherUser: {
        id: '1002',
        name: '对方',
        avatar: 'https://rbtnet.oss-cn-hangzhou.aliyuncs.com/f58cad729ce47acb65666e57496f5e2e0c8badfec8355cfc7d6f2645f8738e60.jpeg',
        onlineStatus: false,
        canAddWechat: false,  // 添加默认值
        age: 0,
        gender: '',
        city: '',
        signature: '',
        albums: [],
        interestTags: [],
        vip: false,
      },
      keyboardHeight: 0, // 键盘高度
      // 添加表情列表数据
      emojiList: [
        // 这里可以替换为使用图片URL的表情对象
        // 例如：{ id: 'smile', name: '微笑', url: '/static/emoji/smile.png' }
        // 但为了让修改更简单，我们先尝试使用emoji字符
        '😀', '😃', '😄', '😁', '😆', '😅', '😂', '🤣', '😊', '😇',
        '🙂', '🙃', '😉', '😌', '😍', '🥰', '😘', '😗', '😙', '😚',
        '😋', '😛', '😝', '😜', '🤪', '🤨', '🧐', '🤓', '😎', '🤩',
        '🥳', '😏', '😒', '😞', '😔', '😟', '😕', '🙁', '☹️', '😣',
        '😖', '😫', '😩', '🥺', '😢', '😭', '😤', '😠', '😡', '🤬',
        '👍', '👎', '👊', '✊', '🤛', '🤜', '🤝', '👏', '🙌', '👐',
        '❤️', '🧡', '💛', '💚', '💙', '💜', '🖤', '💔', '❣️', '💕',
        '🐶', '🐱', '🐭', '🐹', '🐰', '🦊', '🐻', '🐼', '🐨', '🐯'
      ],
      wsListenerId: '', // WebSocket消息监听器ID
      latestReceivedMessageId: null, // 最新接收到的消息ID，用于标记已读
      unreadMessageIds: [],// 存储未读消息ID列表
	  pageHide: false,
      showSubscribe: false, // 控制订阅消息弹窗显示
      lastMessageContent: '', // 最近发送的消息内容
      messageCounter: 0, // 消息计数器，用于控制订阅提示频率
	  // 添加VIP弹窗控制变量
	  isVipModalVisible: false,
      // 举报相关变量
      showReportPopup: false,
      reportData: {
        id: '', // 将在showChatOptions中设置为对方的userId
        type: 'user', // 举报类型为用户
        userId: '' // 被举报用户ID
      },
      // 消息去重机制：记录已处理的消息ID
      processedMessageIds: new Set(),
      // 消息ID过期时间（毫秒），避免内存无限增长
      messageIdExpireTime: 5 * 60 * 1000 // 5分钟
    }
  },
  onLoad(option) {
    // 获取传递的用户ID
    const userId = option.id;
    if (userId) {
	  this.otherUser.id = userId;
      // 从API获取用户信息
      this.loadUserInfo(userId);

      // 添加WebSocket消息监听
      this.setupWebSocketListener();
    } else {
      uni.showToast({
        title: '用户ID不存在',
        icon: 'none'
      });
      setTimeout(() => {
        uni.navigateBack();
      }, 1500);
    }
  },
  onUnload() {
    // 页面卸载时移除WebSocket消息监听器
    if (this.wsListenerId) {
      this.$webSocketManager.removeListener(this.wsListenerId);
      this.wsListenerId = '';
      console.log('聊天页面WebSocket监听器已移除');
    }

    // 清理已处理的消息ID，释放内存
    this.clearProcessedMessages();
  },
  onHide() {
	console.log('页面隐藏');
  	this.pageHide = true;
  },
  methods: {
    // 添加config模块的fetchSystemConfig方法映射
    ...mapActions('config', ['fetchSystemConfig']),
    // 加载用户信息
    loadUserInfo(userId) {
      // 调用获取用户信息的API
      getUserById(userId).then(response => {
        if (response) {
          const userData = response;
          // 更新页面中的用户信息
          this.otherUser = {
            id: userData.id,
            name: userData.nickname || `用户${userData.id}`,
            avatar: userData.avatar || 'https://rbtnet.oss-cn-hangzhou.aliyuncs.com/f58cad729ce47acb65666e57496f5e2e0c8badfec8355cfc7d6f2645f8738e60.jpeg',
            onlineStatus: userData.onlineStatus,
            canAddWechat: userData.canAddWechat, // 从接口返回数据中获取canAddWechat值
            // 添加新的用户信息字段
            age: userData.age || 0,
            gender: userData.sexText || '',
            city: userData.city || '未知',
            signature: userData.signature || '',
            albums: userData.albums || [],
            interestTags: userData.interestTags || [],
            wechat: userData.wechat || '',
            vip: userData.vip || false,
          };
        } else {
          // 处理没有获取到用户信息的情况
          uni.showToast({
            title: '无法获取用户信息',
            icon: 'none'
          });
        }
      }).catch(error => {
        console.error('获取用户信息失败:', error);
        uni.showToast({
          title: '获取用户信息失败',
          icon: 'none'
        });
      }).finally(() => {

      });
    },
    // 处理查询消息
    handleQueryMessages(params) {
      const { pageNo, pageSize, lastMessageId, callback } = params;

      // 准备请求参数
      const requestParams = {
        targetId: this.otherUser.id,
        //targetType: 1, // 单聊类型
        pageSize: pageSize,
        messageId: lastMessageId // 直接使用传过来的lastMessageId
      };

      console.log('查询消息参数:', requestParams); // 添加日志便于调试

      // 调用消息分页API
      getMessagePage(requestParams).then(response => {
        if (response) {
          const messages = this.convertMessagesFromApi(response);
          callback(messages);

          // 记录最后一条消息ID，调试用
          if (messages && messages.length > 0) {
            console.log('最后一条消息ID:', messages[messages.length - 1].id);

            // 添加判断，对于对方发送的未读消息，自动标记为已读
            const unreadMessages = messages.filter(msg => !msg.isSelf && !msg.isRead);

            if (unreadMessages.length > 0) {
              console.log('发现历史未读消息，自动标记为已读:', unreadMessages.length, '条');
              // 调用专门处理历史消息已读的方法
              this.markHistoryMessagesAsRead(unreadMessages);
            }

            // 页面加载完成后检查是否显示添加微信提示
            if (pageNo === 1) {
              setTimeout(() => {
                this.$refs.chatContainer.checkAddWeChatTip();
              }, 500);
            }
          }
        } else {
          callback([]);
        }
      }).catch(error => {
        console.error('获取消息列表失败:', error);
        uni.showToast({
          title: '获取消息列表失败',
          icon: 'none'
        });
        callback([]);
      });
    },

    // 将API返回的消息转换为前端需要的格式
    convertMessagesFromApi(messageList) {
      // 获取当前用户ID - 直接使用计算属性
      const currentUserId = this.currentUser.id;

      if (!Array.isArray(messageList) || messageList.length === 0) {
        return [];
      }

      // 转换消息
      const messages = messageList.map((item, index) => {
        const isSelf = item.userId === currentUserId;
        const showTime = index === 0 ||
                         (index > 0 && this.shouldShowTime(messageList[index-1].sendTime, item.sendTime));

        return {
          id: item.id,
          content: item.content,
          time: this.formatTime(new Date(item.sendTime)),
          showTime: showTime,
          isSelf: isSelf,
          userId: item.userId,
          userName: isSelf ? this.currentUser.name : this.otherUser.name,
          avatar: isSelf ? this.currentUser.avatar : this.otherUser.avatar,
          sendStatus: 'success',
          isRead: item.readStatus,
          status: item.status || 0, // 添加状态字段，默认为0（正常）
          isRecalled: item.status === 2,
          rejectedReason: item.reason, // 添加违规原因字段
          timestamp: new Date(item.sendTime).getTime(),
          messageType: item.type === 1 ? 'text' :
                      item.type === 2 ? 'image' :
                      item.type === 3 ? 'voice' :
                      item.type === 4 ? 'video' :
                      item.type === 5 ? 'file' :
                      item.type === 6 ? 'location' :
                      item.type === 7 ? 'contact' :
                      item.type === 8 ? 'wechatRequest' :
                      item.type === 9 ? 'wechatApproved' :
                      item.type === 80 ? 'wechatApprovedStatus' : 'text',
          // 如果是图片消息，需要设置imageUrl属性
          ...(item.type === 2 ? { imageUrl: JSON.parse(item.content).url } : {})
        };
      });

      // 处理违规消息，为每个违规消息添加一条系统提示消息
      const finalMessages = [];
      for (let i = 0; i < messages.length; i++) {
        const message = messages[i];
        // 如果是违规消息，添加一条系统提示消息
        if (message.status === 3) {
          const systemMessage = {
            id: `system_${message.id}`,
            content: `⚠️ 温馨提示：上述消息内容不当已被屏蔽\n${message.rejectedReason ? '原因：' + message.rejectedReason : '请发布健康、友好的内容，共建和谐社区'}`,
            time: message.time,
            showTime: false,
            isSelf: false,
            isSystemMessage: true,
            userId: 'system',
            userName: '系统提示',
            avatar: '',
            sendStatus: 'success',
            isRead: true,
            timestamp: message.timestamp + 1, // 确保系统消息排在违规消息后面
            messageType: 'system'
          };
          finalMessages.push(systemMessage);
        }

		finalMessages.push(message);

      }

      return finalMessages;
    },

    // 判断是否应该显示时间
    shouldShowTime(prevTime, currTime) {
      // 如果消息间隔超过5分钟，显示时间
      const prev = new Date(prevTime).getTime();
      const curr = new Date(currTime).getTime();
      return (curr - prev) > 5 * 60 * 1000;
    },

    // 处理发送文本消息
    handleSendText(params) {
      const { text } = params;

      // 保存最后发送的消息内容用于订阅示例
      this.lastMessageContent = text;

      // 创建临时消息对象，先显示在界面上
      const tempMessageId = `temp_${Date.now()}`;
      const newMessage = {
        id: tempMessageId,
        content: text,
        time: this.formatTime(new Date()),
        showTime: true,
        isSelf: true,
        userId: this.currentUser.id,
        userName: this.currentUser.name,
        avatar: this.currentUser.avatar,
        sendStatus: 'sending', // 设置为发送中
        isRead: false,
        status: 0, // 初始状态为正常
        timestamp: Date.now(),
        messageType: 'text'
      };

      // 添加到消息列表
      this.$refs.chatContainer.addMessage(newMessage);

      // #ifdef MP-WEIXIN
      // 增加消息计数器
      this.messageCounter++;

      // 获取消息计数器阈值
      const threshold = MESSAGE_COUNTER_THRESHOLD.CHAT || 1;

      // 检查是否需要显示订阅提示（每发送threshold条消息检查一次）
      if (this.messageCounter >= threshold) {
        // 重置计数器
        this.messageCounter = 0;

        // 检查是否已订阅
        if (!SubscribeManager.isSubscribed(STORAGE_KEYS.POST.SUBSCRIBED)) {
          // 未订阅用户，检查是否需要显示提示
          if (SubscribeManager.shouldShowPrompt(STORAGE_KEYS.POST.SUBSCRIBED, STORAGE_KEYS.POST.LAST_PROMPT, 'POST')) {
            // 记录提示时间
            SubscribeManager.recordPromptTime(STORAGE_KEYS.POST.LAST_PROMPT);
            // 显示订阅弹窗
            this.showSubscribe = true;
          }
        } else {
          // 已订阅用户，执行静默订阅续期
          SubscribeManager.silentSubscribe(
              'POST_ALL',
              STORAGE_KEYS.POST.SUBSCRIBED,
              STORAGE_KEYS.POST.SUBSCRIBE_TIME,
              STORAGE_KEYS.POST.LAST_PROMPT,
              (result) => {

                // 只有订阅成功接受的情况下才执行跳转
                if (result && result.accepted) {

                } else if (result && result.rejected) {
                  // 用户拒绝了订阅，引导用户去设置页面开启权限（已在封装里面处理）
                } else {

                }
              }
          );
        }
      }
      // #endif

      // 调用发送消息API
      const data = {
        receiverId: this.otherUser.id,
        receiverType: 1, // 假设是单聊
        type: 1, // 文本消息
        content: text
      };

      sendMessage(data).then(response => {
        // 发送成功，使用返回的消息ID更新临时消息
        if (response) {
          this.$refs.chatContainer.updateMessage(tempMessageId, {
            id: response.messageId, // 使用真实的消息ID
            sendStatus: 'success'
          });
        } else {
          // 发送失败
          this.$refs.chatContainer.updateMessage(tempMessageId, {
            sendStatus: 'failed'
          });
        }
      }).catch(error => {
        console.error('发送消息失败:', error);
        // 显示发送失败状态
        this.$refs.chatContainer.updateMessage(tempMessageId, {
          sendStatus: 'failed'
        });
        if(error.code === 1001000007){
          uni.showModal({
            title: '会员特权',
            content: error.msg,
            showCancel: false,
            success: (res) => {
              if (res.confirm) {
                // 显示VIP弹窗
                this.isVipModalVisible = true;
              }
            }
          });
        }else{
          uni.showToast({
            title: error.msg,
            icon: 'none'
          });
        }
      });
    },

    // 处理工具点击
    handleToolClick(params) {
      const { tool } = params;

      switch (tool) {
        case 'image':
          this.chooseImage();
          break;
        case 'camera':
          this.takePhoto();
          break;
        case 'video':
          this.chooseVideo();
          break;
        case 'location':
          this.chooseLocation();
          break;
        case 'file':
          this.chooseFile();
          break;
        case 'collection':
          this.openCollection();
          break;
        case 'voice':
          this.startVoiceRecord();
          break;
        case 'video-call':
          this.startVideoCall();
          break;
        case 'audio-call':
          this.startAudioCall();
          break;
        case 'contact':
          this.shareContact();
          break;
      }
    },

    // 处理撤回消息
    handleRecallMessage(params) {
      const { messageId } = params;

      // 获取消息对象
      const message = this.$refs.chatContainer.getMessage(messageId);
      if (!message) return;

      // 检查消息是否在可撤回时间范围内（5分钟）
      const now = Date.now();
      const messageTime = message.timestamp;
      const timeDiff = now - messageTime;

      // 如果超过5分钟，提示用户并拒绝撤回
      if (timeDiff > 300000) { // 5 * 60 * 1000 = 300000毫秒
        uni.showToast({
          title: '超过5分钟的消息无法撤回',
          icon: 'none'
        });
        return;
      }

      recallMessage({ messageId }).then(response => {
        if (response) {
          // 更新消息为撤回状态
          this.$refs.chatContainer.updateMessage(messageId, {
            content: '你撤回了一条消息',
            isRecalled: true
          });
        } else {
          uni.showToast({
            title: '撤回失败',
            icon: 'none'
          });
        }
      }).catch(error => {
        console.error('撤回消息失败:', error);
        uni.showToast({
          title: '撤回失败',
          icon: 'none'
        });
      });
    },

    // 处理删除消息
    handleDeleteMessage(params) {
      const { messageId } = params;

      // 获取消息对象，用于记录是否为对方消息
      const message = this.$refs.chatContainer.getMessage(messageId);
      const isOtherUserMessage = message && !message.isSelf;

      console.log('删除消息:', messageId, isOtherUserMessage ? '对方消息' : '自己的消息');

      deleteMessage({ messageId }).then(response => {
        if (response) {
          // 从列表中删除消息
          this.$refs.chatContainer.deleteMessageById(messageId);

          // 提示用户删除成功
          uni.showToast({
            title: '删除成功',
            icon: 'success',
            duration: 1500
          });
        } else {
          uni.showToast({
            title: '删除失败',
            icon: 'none'
          });
        }
      }).catch(error => {
        console.error('删除消息失败:', error);
        uni.showToast({
          title: '删除失败',
          icon: 'none'
        });
      });
    },

    // 处理消息已读
    handleMessageRead(messageId) {
      readMessage({ messageId }).then(response => {
        // 标记成功，不需要特殊处理
      }).catch(error => {
        console.error('标记已读失败:', error);
      });
    },

    // 处理重发消息
    handleResendMessage(params) {
      const { messageId } = params;

      // 获取原消息内容
      const message = this.$refs.chatContainer.getMessage(messageId);
      if (!message) return;

      // 更新消息状态为发送中
      this.$refs.chatContainer.updateMessage(messageId, {
        sendStatus: 'sending'
      });

      // 准备重发数据
      const data = {
        receiverId: this.otherUser.id,
        receiverType: 1, // 假设是单聊
        type: message.messageType === 'text' ? 1 :
              message.messageType === 'image' ? 2 :
              message.messageType === 'voice' ? 3 :
              message.messageType === 'video' ? 4 :
              message.messageType === 'file' ? 5 :
              message.messageType === 'location' ? 6 :
              message.messageType === 'contact' ? 7 : 1,
        content: message.content
      };

      // 调用发送API
      sendMessage(data).then(response => {
        if (response) {
          // 更新消息ID和状态
          this.$refs.chatContainer.updateMessage(messageId, {
            id: response.messageId,
            sendStatus: 'success'
          });
        } else {
          // 重发失败
          this.$refs.chatContainer.updateMessage(messageId, {
            sendStatus: 'failed'
          });
        }
      }).catch(error => {
        console.error('重发消息失败:', error);
        this.$refs.chatContainer.updateMessage(messageId, {
          sendStatus: 'failed'
        });

		if(error.code === 1001000007){
			uni.showModal({
			  title: '会员特权',
			  content: error.msg,
			  showCancel: false,
			  success: (res) => {
			    if (res.confirm) {
			      // 显示VIP弹窗
			      this.isVipModalVisible = true;
			    }
			  }
			});
		}else{
			uni.showToast({
			  title: error.msg,
			  icon: 'none',
			  duration: 2000
			});
		}

      });
    },

    // 处理举报用户
    handleReportUser() {
      console.log('举报用户：用户ID=', this.otherUser.id);
      
      // 设置举报数据
      this.reportData = {
        id: this.otherUser.id,
        type: 'user',
        userId: this.otherUser.id // 被举报用户ID
      };
      
      // 显示举报弹窗
      this.showReportPopup = true;
    },

    // 处理添加微信
    handleAddWeChat(userId) {
      console.log('添加微信请求：用户ID=', userId);

      // 先弹出确认对话框
      uni.showModal({
        title: '添加微信',
        content: '是否添加对方微信？',
        confirmText: '添加',
        success: (res) => {
          if (res.confirm) {
            // 用户确认后，调用API获取微信号
            getUserWechat(userId || this.otherUser.id).then(response => {
              const wechatId = response || '';
              if (wechatId) {
                // 显示微信号弹窗
                this.showWechatModal(wechatId, this.otherUser.name);
              } else {
                uni.showToast({
                  title: '获取微信号失败',
                  icon: 'none'
                });
              }
            }).catch(error => {
              // 记录错误并显示获取失败提示
              console.error('获取微信号失败:', error);

			  if(error.code === 1004001102){
			  	uni.showModal({
			  	  title: '会员特权',
			  	  content: error.msg,
				  showCancel: false,
			  	  success: (res) => {
			  	    if (res.confirm) {
			  	      // 显示VIP弹窗
			  	      this.isVipModalVisible = true;
			  	    }
			  	  }
			  	});
			  }else{
			  	uni.showToast({
			  	  title: error.msg,
			  	  icon: 'none',
			  	  duration: 2000
			  	});
			  }

            });
          }
        }
      });
    },

    // 显示微信号弹窗
    showWechatModal(wechatId, username) {
      uni.showModal({
        title: '微信号',
        content: `${username}的微信号：${wechatId}`,
        confirmText: '复制',
        cancelText: '关闭',
        success: (res) => {
          if (res.confirm) {
            // 复制微信号到剪贴板
            uni.setClipboardData({
              data: wechatId,
              success: () => {
                uni.showToast({
                  title: '微信号已复制',
                  icon: 'success'
                });
              }
            });
          }
        }
      });
    },

    // 发送图片消息
    sendImageMessage(imageUrl) {
      // 创建临时消息对象
      const tempMessageId = `temp_${Date.now()}`;
      const newMessage = {
        id: tempMessageId,
        content: '[图片]',
        imageUrl: imageUrl,
        time: this.formatTime(new Date()),
        showTime: true,
        isSelf: true,
        userId: this.currentUser.id,
        userName: this.currentUser.name,
        avatar: this.currentUser.avatar,
        sendStatus: 'sending',
        isRead: false,
        status: 0, // 初始状态为正常
        timestamp: Date.now(),
        messageType: 'image'
      };

      // 添加到消息列表
      this.$refs.chatContainer.addMessage(newMessage);

      // 使用通用的上传文件API
      uploadFile({
        filePath: imageUrl,
        fileType: 'chatImage',
        onProgress: (progress) => {
          console.log('上传进度:', progress);
        }
      }).then(result => {
        // 获取图片信息，用于保存宽高
        uni.getImageInfo({
          src: imageUrl,
          success: (imageInfo) => {
            // 构建图片消息内容
            const imageContent = JSON.stringify({
              url: result,
              width: imageInfo.width || 0,
              height: imageInfo.height || 0
            });

            // 发送消息
            const data = {
              receiverId: this.otherUser.id,
              receiverType: 1,
              type: 2, // 图片类型
              content: imageContent
            };

            sendMessage(data).then(response => {
              if (response) {
                this.$refs.chatContainer.updateMessage(tempMessageId, {
                  id: response.messageId,
                  sendStatus: 'success'
                });
              } else {
                this.$refs.chatContainer.updateMessage(tempMessageId, {
                  sendStatus: 'failed'
                });
              }
            }).catch(error => {
              console.error('发送图片消息失败:', error);
              this.$refs.chatContainer.updateMessage(tempMessageId, {
                sendStatus: 'failed'
              });

			  if(error.code === 1001000007){
			  	uni.showModal({
			  	  title: '会员特权',
			  	  content: error.msg,
				  showCancel: false,
			  	  success: (res) => {
			  	    if (res.confirm) {
			  	      // 显示VIP弹窗
			  	      this.isVipModalVisible = true;
			  	    }
			  	  }
			  	});
			  }else{
			  	uni.showToast({
			  	  title: error.msg,
			  	  icon: 'none',
			  	  duration: 2000
			  	});
			  }

            });
          },
          fail: (err) => {
            console.error('获取图片信息失败:', err);
            // 即使获取图片信息失败，也尝试发送消息
            const imageContent = JSON.stringify({
              url: result,
              width: 0,
              height: 0
            });

            const data = {
              receiverId: this.otherUser.id,
              receiverType: 1,
              type: 2,
              content: imageContent
            };

            sendMessage(data).then(response => {
              if (response) {
                this.$refs.chatContainer.updateMessage(tempMessageId, {
                  id: response.messageId,
                  sendStatus: 'success'
                });
              } else {
                this.$refs.chatContainer.updateMessage(tempMessageId, {
                  sendStatus: 'failed'
                });
              }
            }).catch(error => {
              console.error('发送图片消息失败:', error);
              this.$refs.chatContainer.updateMessage(tempMessageId, {
                sendStatus: 'failed'
              });
            });
          }
        });
      }).catch(err => {
        console.error('图片上传失败:', err);
        this.$refs.chatContainer.updateMessage(tempMessageId, {
          sendStatus: 'failed'
        });
        uni.showToast({
          title: '图片上传失败',
          icon: 'none'
        });
      });
    },

    // 格式化时间
    formatTime(date) {
      const now = new Date();
      const today = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime();
      const yesterday = today - 86400000;
      const messageDate = new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime();

      let prefix = '';
      if (messageDate === today) {
        prefix = '今天 ';
      } else if (messageDate === yesterday) {
        prefix = '昨天 ';
      } else {
        prefix = `${date.getMonth() + 1}月${date.getDate()}日 `;
      }

      return `${prefix}${this.padZero(date.getHours())}:${this.padZero(date.getMinutes())}`;
    },

    // 数字补零
    padZero(num) {
      return num < 10 ? `0${num}` : num;
    },

    // 返回上一页
    goBack() {
      // 返回前确保清理监听器
      if (this.wsListenerId) {
        this.$webSocketManager.removeListener(this.wsListenerId);
        this.wsListenerId = '';
      }
      uni.navigateBack();
    },

    // 显示聊天选项
    showChatOptions() {
      // 调试日志，确认方法被触发
      console.log('showChatOptions方法被触发');
      uni.showActionSheet({
        itemList: ['清空聊天记录', '举报拉黑用户'],
        success: (res) => {
          console.log('选择了第' + (res.tapIndex + 1) + '个选项');
          switch(res.tapIndex) {
            case 0: // 清空聊天记录
              this.confirmClearChat();
              break;
            case 1: // 举报
              // 设置举报数据
              this.reportData = {
                id: this.otherUser.id,
                type: 'user',
                userId: this.otherUser.id // 被举报用户ID
              };
              // 显示举报弹窗
              this.showReportPopup = true;
              break;
            default:
              uni.showToast({
                title: '功能开发中',
                icon: 'none'
              });
          }
        }
      });
    },

    // 确认清空聊天记录
    confirmClearChat() {
      uni.showModal({
        title: '提示',
        content: '确定要清空聊天记录吗？',
        success: (res) => {
          if (res.confirm) {
            // 调用清空API
            deleteAllMessages({
              targetId: this.otherUser.id,
              targetType: 1
            }).then(response => {
              if (response) {
                this.$refs.chatContainer.clear();
                uni.showToast({
                  title: '聊天记录已清空',
                  icon: 'success'
                });
              } else {
                uni.showToast({
                  title: '清空失败',
                  icon: 'none'
                });
              }
            }).catch(error => {
              console.error('清空聊天记录失败:', error);
              uni.showToast({
                title: '清空失败',
                icon: 'none'
              });
            });
          }
        }
      });
    },

    // 处理键盘高度变化
    handleKeyboardHeightChange(res) {
      this.keyboardHeight = res.height;
    },

    // 处理键盘隐藏
    handleKeyboardHide() {
      this.keyboardHeight = 0;
    },

    // 选择图片
    chooseImage() {
      uni.chooseImage({
        count: 9, // 最多可选择的图片数量
        success: (res) => {
          const tempFilePaths = res.tempFilePaths;
          // 这里可以将图片上传到服务器，然后发送消息
          // 此处仅做演示，直接发送本地图片路径作为消息
          this.sendImageMessage(tempFilePaths[0]);
        }
      });
    },

	// VIP购买成功回调
	onVipPurchaseSuccess(purchaseInfo) {
	  console.log('VIP购买成功', purchaseInfo);
	},

    // 处理显示VIP弹窗事件
    handleShowVipModal(data) {
      console.log('显示VIP弹窗:', data);
      
      // 显示VIP弹窗
      this.isVipModalVisible = true;
    },

    // 拍照
    takePhoto() {
      uni.chooseImage({
        count: 1,
        sourceType: ['camera'],
        success: (res) => {
          const tempFilePath = res.tempFilePaths[0];
          this.sendImageMessage(tempFilePath);
        }
      });
    },

    // 选择视频
    chooseVideo() {
      uni.chooseVideo({
        success: (res) => {
          uni.showToast({
            title: '视频功能开发中',
            icon: 'none'
          });
        }
      });
    },

    // 选择位置
    chooseLocation() {
      uni.chooseLocation({
        success: (res) => {
          uni.showToast({
            title: '位置功能开发中',
            icon: 'none'
          });
        },
        fail: () => {
          uni.showToast({
            title: '获取位置失败',
            icon: 'none'
          });
        }
      });
    },

    // 选择文件（H5环境可用）
    chooseFile() {
      // #ifdef H5
      // 使用H5的input type="file"来选择文件
      // #endif

      // #ifndef H5
      uni.showToast({
        title: '文件功能在当前平台不可用',
        icon: 'none'
      });
      // #endif
    },

    // 打开收藏
    openCollection() {
      uni.showToast({
        title: '收藏功能开发中',
        icon: 'none'
      });
    },

    // 开始语音录制
    startVoiceRecord() {
      uni.showToast({
        title: '语音功能开发中',
        icon: 'none'
      });
    },

    // 分享联系人名片
    shareContact() {
      uni.showToast({
        title: '名片功能开发中',
        icon: 'none'
      });
    },

    // 开始视频通话
    startVideoCall() {
      this.startCall('video', '1');
    },

    // 开始语音通话
    startAudioCall() {
      this.startCall('audio', '0');
    },

    // 统一的通话启动方法
    async startCall(callType, typeValue) {
      try {
        const title = callType === 'video' ? '视频通话' : '语音通话';

        // 显示发起通话的提示
        uni.showLoading({
          title: `正在发起${title}...`,
          mask: true
        });

        // 转换通话类型：前端 '0'=语音，'1'=视频 → 后端 1=语音，2=视频
        const apiCallType = typeValue === '0' ? 1 : 2;

        // 调用后端邀请接口
        const callData = {
          calleeId: this.otherUser.id,
          calleeType: 1, // 默认用户类型为1
          callType: apiCallType
        };

        console.log('发起通话邀请，参数:', callData);

        const response = await initiateCall(callData);

        uni.hideLoading();

        if (response) {
          console.log('通话邀请发送成功，callId:', response.data);

          // 构建webview页面参数，使用后端返回的callId
          const URLSearchParamsClass = getURLSearchParams();
          const webviewParams = new URLSearchParamsClass({
            targetId: this.otherUser.id,
            name: this.otherUser.name || '用户',
            avatar: this.otherUser.avatar || 'https://rbtnet.oss-cn-hangzhou.aliyuncs.com/f58cad729ce47acb65666e57496f5e2e0c8badfec8355cfc7d6f2645f8738e60.jpeg',
            callId: response, // 使用后端返回的通话ID，在data字段中
            callType: typeValue,     // callType=1 表示视频通话，callType=0 表示语音通话
            // 发起通话时不传递 isIncomingCall，默认为发起状态
            title: title,
            currentUserId: this.currentUser.id // 添加当前用户ID用于WebSocket消息判断
          });

          // 打开视频通话中转页面（支持微信小程序webview）
          uni.navigateTo({
            url: `/pages/video-call-transfer/index?${webviewParams.toString()}`,
            fail: (err) => {
              console.error(`打开${title}页面失败:`, err);
              uni.showToast({
                title: `${title}功能暂不可用`,
                icon: 'none'
              });
            }
          });
        } else {
          throw new Error('发起通话失败，未返回通话ID');
        }
      } catch (error) {
        console.error(`启动${callType === 'video' ? '视频' : '语音'}通话失败:`, error);

        uni.hideLoading();

        // 显示具体错误信息
        uni.showToast({
          title: error.message || error.msg || `发起${title}失败`,
          icon: 'none',
          duration: 2000
        });
      }
    },

    // 设置WebSocket消息监听
    setupWebSocketListener() {
      // 生成唯一监听器ID
      this.wsListenerId = `chat_${this.otherUser.id}_${Date.now()}`;

      // 添加消息监听器
      this.$webSocketManager.addListener(this.wsListenerId, (message) => {
        // 处理接收到的消息
        this.handleWebSocketMessage(message);
      });

      console.log('聊天页面WebSocket监听器已设置');
    },

    // 处理WebSocket接收到的消息
    handleWebSocketMessage(message) {
      // 判断消息类型
      if (!message || !message.type) return;

      console.log('聊天页面收到WebSocket消息:', message);

      // 添加对 im.message.send 类型消息的处理
      if (message.type === 'im.message.send') {
        try {
          // 解析消息内容
          const msgData = typeof message.content === 'string' ?
            JSON.parse(message.content) : message.content;

          // 获取当前用户ID - 直接使用计算属性
          const currentUserId = this.currentUser.id;

          // 检查消息是否与当前聊天有关（发送给当前用户 且 来自当前聊天对象）
          if (msgData.toUserId == currentUserId && msgData.fromUserId == this.otherUser.id) {
            console.log('收到当前聊天对象发来的新消息:', msgData);

            // 保存最新消息ID用于标记已读
            this.latestReceivedMessageId = msgData.messageId;

            // 创建消息对象
            const newMessage = {
              id: msgData.messageId,
              content: msgData.content,
              time: this.formatTime(new Date(msgData.sendTime || new Date())),
              showTime: true,
              isSelf: false, // 收到的消息一定是对方发送的
              userId: msgData.fromUserId,
              userName: msgData.fromUserNickname || this.otherUser.name,
              avatar: msgData.fromUserAvatar || this.otherUser.avatar,
              sendStatus: 'success',
              isRead: false,
              status: msgData.status || 0, // 添加状态字段
              rejectedReason: msgData.reason, // 添加违规原因字段
              timestamp: msgData.sendTime ? new Date(msgData.sendTime).getTime() : Date.now(),
              messageType: msgData.type === 1 ? 'text' :
                          msgData.type === 2 ? 'image' :
                          msgData.type === 3 ? 'voice' :
                          msgData.type === 4 ? 'video' :
                          msgData.type === 5 ? 'file' :
                          msgData.type === 6 ? 'location' :
                          msgData.type === 7 ? 'contact' :
                          msgData.type === 8 ? 'wechatRequest' :
                          msgData.type === 9 ? 'wechatApproved' :
                          msgData.type === 80 ? 'wechatApprovedStatus' : 'text',
              // 如果是图片消息，设置imageUrl属性
              ...(msgData.type === 2 ? { imageUrl: JSON.parse(msgData.content).url } : {})
            };

            // 添加到消息列表
            this.$refs.chatContainer.addMessage(newMessage);

            // 标记为已读
			if(this.pageHide) {
				// 添加到未读消息ID列表
				if (msgData.messageId && !this.unreadMessageIds.includes(msgData.messageId)) {
				  this.unreadMessageIds.push(msgData.messageId);
				}
			}else{
				this.markMessageAsRead(msgData.messageId);
			}
          }
        } catch (error) {
          console.error('处理发送消息失败:', error);
        }
      }

      // 处理消息状态更新类型
      else if (message.type === 'im.message.status') {
        try {
          const statusData = typeof message.content === 'string' ?
            JSON.parse(message.content) : message.content;

          // 更新消息状态（如已读状态）
          if (statusData.messageId && statusData.status) {
            // 更新本地消息状态
            this.$refs.chatContainer.updateMessage(statusData.messageId, {
              isRead: statusData.status === 'READ'
            });
          }
        } catch (error) {
          console.error('处理消息状态更新失败:', error);
        }
      }

      // 处理消息已读类型
      else if (message.type === 'im.message.read') {
        try {
          // 这种类型的消息内容直接是消息ID
          let messageId = message.content;
          console.log('收到消息已读通知:', messageId);

          if (messageId) {
            // 获取当前用户ID - 直接使用计算属性
            const currentUserId = this.currentUser.id;

            // 更新消息已读状态 - 仅更新自己发送的消息
            const targetMessage = this.$refs.chatContainer.getMessage(messageId);
			console.log('查询到:', targetMessage);
            if (targetMessage && targetMessage.isSelf) {
              this.$refs.chatContainer.updateMessage(messageId, {
                isRead: true
              });
              console.log('消息已标记为已读状态:', messageId);
            }
          }
        } catch (error) {
          console.error('处理消息已读更新失败:', error);
        }
      }

      // 处理消息撤回类型
      else if (message.type === 'im.message.recall') {
        try {
          // 解析消息内容
          const recallData = typeof message.content === 'string' ?
            JSON.parse(message.content) : message.content;

          console.log('收到消息撤回通知:', recallData);

          if (recallData && recallData.messageId) {
            // 获取被撤回的消息
            const targetMessage = this.$refs.chatContainer.getMessage(recallData.messageId);

            if (targetMessage) {
              // 区分是自己撤回的还是对方撤回的
              const recallText = targetMessage.isSelf ?
                '你撤回了一条消息' :
                `${this.otherUser.name}撤回了一条消息`;

              // 更新消息为撤回状态
              this.$refs.chatContainer.updateMessage(recallData.messageId, {
                content: recallText,
                status: 2
              });

              console.log('消息已更新为撤回状态:', recallData.messageId);
            } else {
              console.log('未找到要撤回的消息:', recallData.messageId);
            }
          }
        } catch (error) {
          console.error('处理消息撤回失败:', error);
        }
      }

      // 处理消息审核被拒绝类型（内容违规）
      else if (message.type === 'im.message.audit.rejected') {
        try {
          // 解析消息内容
          const auditData = typeof message.content === 'string' ?
            JSON.parse(message.content) : message.content;

          console.log('收到消息审核被拒绝通知:', auditData);

          if (auditData && auditData.messageId) {
            // 获取被拒绝的消息
            const targetMessage = this.$refs.chatContainer.getMessage(auditData.messageId);

            if (targetMessage) {
              // 更新消息为违规状态 (status=3)
              this.$refs.chatContainer.updateMessage(auditData.messageId, {
                status: 3,
                rejectedReason: auditData.reason || '内容不当，已被屏蔽'
              });

              console.log('消息已更新为违规状态:', auditData.messageId, '原因:', auditData.reason);

              // 添加一条系统提示消息，显示在聊天中间
              const systemMessage = {
                id: `system_${Date.now()}`,
                content: `⚠️ 温馨提示：上述消息内容不当已被屏蔽\n${auditData.reason ? '原因：' + auditData.reason : '请发布健康、友好的内容，共建和谐社区'}`,
                time: this.formatTime(new Date()),
                showTime: false,
                isSelf: false, // 系统消息不属于任何一方
                isSystemMessage: true, // 标记为系统消息
                userId: 'system',
                userName: '系统提示',
                avatar: '', // 系统消息不显示头像
                sendStatus: 'success',
                isRead: true,
                timestamp: Date.now(),
                messageType: 'system' // 添加系统消息类型
              };

              // 将系统消息添加到消息列表
              this.$refs.chatContainer.addMessage(systemMessage);
            } else {
              console.log('未找到要标记为违规的消息:', auditData.messageId);
            }
          }
        } catch (error) {
          console.error('处理消息审核被拒绝失败:', error);
        }
      }

      // 处理通话邀请类型（包括语音和视频通话）
      else if (this.isVideoCallInviteMessage(message.type)) {
        try {
          // 解析消息内容
          const callData = typeof message.content === 'string' ?
            JSON.parse(message.content) : message.content;

          console.log('收到通话邀请:', callData);

          // 获取后端提供的消息唯一ID
          const messageId = this.generateMessageId(message, callData);

          // 检查消息是否已经处理过
          if (this.isMessageProcessed(messageId)) {
            console.log('通话邀请消息已处理过，跳过:', {
              callId: messageId,
              messageType: message.type,
              callerId: callData.callerId
            });
            return;
          }

          // 检查是否是给当前用户的通话邀请
          const currentUserId = this.currentUser.id;
          if (callData.callerId == this.otherUser.id) {
            // 标记消息为已处理（使用后端提供的callId）
            this.markMessageAsProcessed(messageId);
            console.log('通话邀请消息已标记为已处理:', {
              callId: messageId,
              isBackendCallId: !!callData.callId,
              messageType: message.type,
              callType: callData.callType === 1 ? '语音通话' : '视频通话'
            });

            // 根据 callType 判断通话类型并处理
            this.handleCallInvite(callData);
          }
        } catch (error) {
          console.error('处理通话邀请失败:', error);
        }
      }

      // 处理其他可能的消息类型...
    },

    // 处理通话邀请（统一处理语音和视频通话）
    handleCallInvite(callData) {
      const isVoiceCall = callData.callType === 1;
      const isVideoCall = callData.callType === 2;

      if (!isVoiceCall && !isVideoCall) {
        console.warn('未知的通话类型:', callData.callType);
        return;
      }

      const callTypeName = isVoiceCall ? '语音通话' : '视频通话';
      console.log(`处理${callTypeName}邀请:`, callData);

             // 构建跳转到webview页面的参数
       const URLSearchParamsClass = getURLSearchParams();
       const params = new URLSearchParamsClass({
         targetId: callData.callerId, // 通话发起者ID
         name: callData.callerInfo?.nickname || callData.callerInfo?.name || this.otherUser.name, // 通话发起者姓名
         avatar: callData.callerInfo?.avatar || this.otherUser.avatar, // 通话发起者头像
         callId: callData.callId, // 通话ID
         callType: isVoiceCall ? '0' : '1', // 0表示语音通话，1表示视频通话
         isIncomingCall: 'true', // 标记这是接收到的通话邀请
         title: callTypeName, // 页面标题
         currentUserId: this.currentUser.id // 添加当前用户ID用于WebSocket消息判断
       });

      // 跳转到视频通话中转页面（支持微信小程序webview）
      uni.navigateTo({
        url: `/pages/video-call-transfer/index?${params.toString()}`,
        success: () => {
          console.log(`成功跳转到${callTypeName}页面`);
        },
        fail: (error) => {
          console.error(`跳转到${callTypeName}页面失败:`, error);
          uni.showToast({
            title: `无法启动${callTypeName}`,
            icon: 'none'
          });
        }
      });
    },

    // 标记消息为已读
    markMessageAsRead(messageId) {
      if (!messageId) return;

      console.log('标记消息已读:', messageId);

      // 调用标记已读API
      readMessage({ messageId }).then(response => {
        console.log('消息已标记为已读');

        // 从未读列表中移除该消息ID
        this.unreadMessageIds = this.unreadMessageIds.filter(id => id !== messageId);
      }).catch(error => {
        console.error('标记消息已读失败:', error);
      });
    },

    // 批量标记消息为已读
    markAllUnreadMessages() {
      if (this.unreadMessageIds.length === 0) return;

      console.log('批量标记未读消息为已读:', this.unreadMessageIds);

      // 逐个标记已读
      const promises = this.unreadMessageIds.map(messageId => {
        return readMessage({ messageId }).then(() => {
          return messageId; // 返回成功处理的消息ID
        }).catch(error => {
          console.error(`标记消息 ${messageId} 已读失败:`, error);
          return null; // 失败返回null
        });
      });

      // 等待所有标记操作完成
      Promise.all(promises).then(results => {
        // 过滤出成功标记的消息ID
        const successIds = results.filter(id => id !== null);
        console.log('成功标记已读的消息:', successIds);

        // 从未读列表中移除已成功标记的消息ID
        this.unreadMessageIds = this.unreadMessageIds.filter(id => !successIds.includes(id));
      });
    },

    // 标记历史消息为已读
    markHistoryMessagesAsRead(unreadMessages) {
      if (!unreadMessages || unreadMessages.length === 0) return;

      console.log('批量标记历史未读消息为已读，共', unreadMessages.length, '条');

      // 对所有未读消息发起批量已读请求
      const promises = unreadMessages.map(message => {
        // 先更新UI状态，避免用户看到未读状态闪烁
        this.$refs.chatContainer.updateMessage(message.id, {
          isRead: true
        });

        // 调用已读API
        return readMessage({ messageId: message.id }).then(() => {
          console.log('历史消息已标记为已读:', message.id);
          return message.id;
        }).catch(error => {
          console.error(`标记历史消息 ${message.id} 已读失败:`, error);
          return null;
        });
      });

      // 处理所有已读请求
      Promise.all(promises).then(results => {
        const successIds = results.filter(id => id !== null);
        console.log('成功标记历史已读的消息数:', successIds.length);
      });
    },

    // 添加继续引导订阅的方法
    continueSubscribeGuide() {
      SubscribeManager.showSubscribeGuide((subscribed) => {
        // 如果仍未订阅，onShow会再次触发处理
      });
    },

    // 添加订阅成功处理方法
    onSubscribeComplete() {
      // 更新状态
      SubscribeManager.silentSubscribe(
          'POST_ALL',
          STORAGE_KEYS.POST.SUBSCRIBED,
          STORAGE_KEYS.POST.SUBSCRIBE_TIME,
          STORAGE_KEYS.POST.LAST_PROMPT,
          (result) => {
            // 关闭弹窗
            this.showSubscribe = false;

            if (result && result.accepted) {

            } else if (result && result.rejected) {
              // 用户拒绝了订阅，引导用户去设置页面开启权限（已在封装里面处理）
            } else {

            }
          }
      );
    },

    // 处理完善微信信息
    handleCompleteWeChat(data) {
      // 判断是否收到完整的数据对象（而不仅仅是userId）
      if (typeof data === 'object' && data !== null) {
        // 如果是弹窗显示请求，不需要处理
        if (data.showPopup) {
          return;
        }

        // 有messageId和wechat数据时，调用API同意微信添加申请
        if (data.messageId && data.wechat) {
          // 调用API同意微信添加申请
          this.approveWeChatRequest(data.messageId, data.wechat, data.targetId);
        }
        return;
      }
    },

    // 添加新方法：同意微信添加申请
    approveWeChatRequest(messageId, wechat, targetId) {
      // 调用API同意微信添加申请
      const apiParams = {
        messageId: messageId,
        wechat: wechat
      };

      // 调用API
      approveWechatRequest(apiParams).then(response => {
        // 先将当前的微信申请消息(类型8)更新为已同意状态(类型80)
        this.$refs.chatContainer.updateMessage(messageId, {
          type: 80,
          messageType: 'wechatApprovedStatus'
        });

        // 不需要前端发送消息，后端已经处理发送消息的逻辑

      }).catch(error => {
        console.error('同意微信申请失败:', error);
        uni.showToast({
          title: error.msg || '处理失败',
          icon: 'none'
        });
      });
    },

    // 处理view-wechat事件
    handleViewWeChat(userId) {
      // 调用API获取对方的微信号
      getUserWechat(userId || this.otherUser.id).then(response => {
        const wechatId = response || '';
        if (wechatId) {
          // 显示微信号弹窗
          this.showWechatModal(wechatId, this.otherUser.name);
        } else {
          uni.showToast({
            title: '获取微信号失败',
            icon: 'none'
          });
        }
      }).catch(error => {
        console.error('获取微信号失败:', error);

        if(error.code === 1004001102){
          uni.showModal({
            title: '会员特权',
            content: error.msg,
            showCancel: false,
            success: (res) => {
              if (res.confirm) {
                // 显示VIP弹窗
                this.isVipModalVisible = true;
              }
            }
          });
        }else{
          uni.showToast({
            title: error.msg || '获取微信号失败',
            icon: 'none',
            duration: 2000
          });
        }
      });
    },

    // 处理举报提交
    handleReportSubmit(reportData) {
      console.log('收到举报提交:', reportData);

      // 显示提交中状态
      uni.showLoading({
        title: '提交中...',
        mask: true
      });

      // 调用举报API
      api.user.createReport(reportData)
        .then(res => {
          uni.showToast({
            title: '举报已提交',
            icon: 'success',
            duration: 1500
          });
          console.log('举报提交成功:', res);
        })
        .catch(err => {
          uni.showToast({
            title: '举报提交失败',
            icon: 'none',
            duration: 1500
          });
          console.error('举报提交失败:', err);
        })
        .finally(() => {
          // 隐藏加载中
          uni.hideLoading();
        });
    },

    // 处理举报取消
    handleReportCancel() {
      console.log('举报取消');
      this.showReportPopup = false;
    },

    // 预览相册图片
    previewImage(currentImage) {
      const images = this.otherUser.albums.map(album => album.imageUrl);
      uni.previewImage({
        urls: images,
        current: currentImage
      });
    },

    // 消息去重相关方法

    /**
     * 获取消息唯一ID
     * @param {Object} message 原始WebSocket消息
     * @param {Object} callData 通话数据
     * @returns {String} 消息唯一ID
     */
    generateMessageId(message, callData) {
      // 优先使用后端提供的callId作为唯一标识
      if (callData.callId) {
        return callData.callId;
      }

      // 如果没有callId，使用timestamp作为备用标识
      if (callData.timestamp) {
        return `${message.type}_${callData.timestamp}`;
      }

      // 最后兜底方案：基于消息类型和发送者ID生成
      return `${message.type}_${callData.callerId || 'unknown'}_${Date.now()}`;
    },

    /**
     * 检查消息是否已经被处理过
     * @param {String} messageId 消息ID
     * @returns {Boolean} 是否已处理
     */
    isMessageProcessed(messageId) {
      return this.processedMessageIds.has(messageId);
    },

    /**
     * 标记消息为已处理
     * @param {String} messageId 消息ID
     */
    markMessageAsProcessed(messageId) {
      // 添加到已处理集合
      this.processedMessageIds.add(messageId);

      // 设置定时器，5分钟后自动清除该消息ID，防止内存无限增长
      setTimeout(() => {
        this.processedMessageIds.delete(messageId);
        console.log('已清除过期消息ID:', messageId);
      }, this.messageIdExpireTime);

      console.log('消息已标记为已处理:', messageId);
      console.log('当前已处理消息数量:', this.processedMessageIds.size);
    },

    /**
     * 清理所有已处理的消息ID（页面销毁时调用）
     */
    clearProcessedMessages() {
      this.processedMessageIds.clear();
      console.log('已清理所有已处理的消息ID');
    },

    /**
     * 判断是否为通话邀请消息
     * @param {String} messageType 消息类型
     * @returns {Boolean} 是否为通话邀请消息
     */
    isVideoCallInviteMessage(messageType) {
      // 支持的通话邀请消息类型（基于后端 ImWebSocketMessageTypeEnum）
      const callInviteTypes = [
        'video.call.invite',        // 后端标准：视频/语音通话邀请
      ];

      return callInviteTypes.includes(messageType);
    },

  },
  // 添加页面生命周期钩子 - 与methods平级
  onShow() {
    // 重新加载系统配置
    this.fetchSystemConfig().then(() => {
      console.log('交友页面重新加载系统配置成功');
    }).catch(error => {
      console.error('交友页面重新加载系统配置失败:', error);
    });

	  this.pageHide = false;
    // 页面显示时，直接标记所有未读消息为已读
    this.markAllUnreadMessages();

    // #ifdef MP-WEIXIN
    // 使用SubscribeManager检查从设置页面返回状态
    SubscribeManager.checkFromSettingReturn(
        // 成功回调 - 用户已授权并接受订阅
        (result) => {

        },
        // 失败回调 - 用户未授权或拒绝订阅
        () => {
          // 如果仍未订阅，继续提示
          this.continueSubscribeGuide();
        },
        // 传递必要的参数
        'POST_ALL',
        STORAGE_KEYS.POST.SUBSCRIBED,
        STORAGE_KEYS.POST.SUBSCRIBE_TIME,
        STORAGE_KEYS.POST.LAST_PROMPT
    );
    // #endif
  },
  computed: {
    // 从config模块获取wxAuditMode
    ...mapGetters('config', ['wxAuditMode']),
    // 从store获取当前用户信息
    currentUser() {
      const userInfo = this.$store.state.user.userInfo;
      // 确保即使在用户信息不存在的情况下也返回合理的默认值
      return userInfo ? {
        id: userInfo.id,
        name: userInfo.nickname || '我',
        avatar: userInfo.avatar || ''
      } : {
        id: uni.getStorageSync('userId') || '',
        name: '我',
        avatar: ''
      };
    },
    // 添加userInfo计算属性，用于传递给VIP弹窗组件
    userInfo() {
      const userState = this.$store.state.user || {};
      const userInfo = userState.userInfo || {};
      return {
        isVip: userInfo.vip === true,
        // 传递原始用户信息和必要的附加属性
        ...userInfo
	  };
	},
  }
}
</script>

<style lang="scss">
.chat-page {
  position: relative;
  width: 100%;
  height: 100vh;
}

/* 霓虹效果图标 */
.neon-icon {
  text-shadow: 0 0 5px rgba(179, 247, 60, 0.7);
  color: #B3F73C;
}

/* 在线状态指示点 */
.user-status-dot {
  display: inline-block;
  width: 12rpx;
  height: 12rpx;
  border-radius: 50%;
  background-color: #666;
  margin-right: 10rpx;
}

.user-status-dot.online {
  background-color: #B3F73C;
  box-shadow: 0 0 5px rgba(179, 247, 60, 0.7);
}

.user-nickname {
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
	max-width: 200rpx;
}

/* 导航栏标题 */
.nav-title {
  font-size: 32rpx;
  font-weight: 500;
  color: #FFFFFF;
  display: flex;
  align-items: center;
}

/* 导航栏右侧图标 */
.nav-right-icon {
  font-size: 40rpx;
  color: #B3F73C;
  padding: 20rpx 10rpx;
}

/* 聊天内容区域 */
.chat-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  width: 100%;
  height: calc(100vh - 90rpx);
  position: relative;
  z-index: 1;
}

/* 操作按钮区域 */
.action-buttons {
  display: flex;
  gap: 12rpx;
  margin-top: 15rpx;
}

/* 微信按钮样式 - 在卡片内 */
.wechat-button-in-card {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 12rpx 20rpx;
  background: linear-gradient(135deg, #07c160, #06ad56);
  border-radius: 25rpx;
  box-shadow: 0 4rpx 12rpx rgba(7, 193, 96, 0.3);
  transition: all 0.3s ease;
  border: 1rpx solid rgba(255, 255, 255, 0.2);
  
  &:active {
    transform: scale(0.95);
    box-shadow: 0 2rpx 8rpx rgba(7, 193, 96, 0.5);
  }
}

/* 举报按钮样式 - 在卡片内 */
.report-button-in-card {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 12rpx 20rpx;
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.1), rgba(255, 255, 255, 0.05));
  border-radius: 25rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.2);
  transition: all 0.3s ease;
  border: 1rpx solid rgba(255, 255, 255, 0.3);
  backdrop-filter: blur(5px);
  
  &:active {
    transform: scale(0.95);
    background: linear-gradient(135deg, rgba(255, 255, 255, 0.15), rgba(255, 255, 255, 0.08));
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.3);
  }
}

.wechat-icon-small {
  width: 32rpx;
  height: 32rpx;
  margin-right: 8rpx;
}

.wechat-text {
  font-size: 24rpx;
  color: #ffffff;
  font-weight: 500;
  text-shadow: 0 1rpx 2rpx rgba(0, 0, 0, 0.1);
}

.report-icon {
  font-size: 28rpx;
  margin-right: 6rpx;
}

.report-text {
  font-size: 24rpx;
  color: rgba(255, 255, 255, 0.9);
  font-weight: 500;
  text-shadow: 0 1rpx 2rpx rgba(0, 0, 0, 0.1);
}

/* 导航栏右侧按钮样式 */
.nav-right-button {
  position: absolute;
  right: 240rpx;
  top: 0;
  padding: 20rpx 10rpx;
  z-index: 999;
}

/* 用户资料卡片样式 */
.user-profile-card {
  background-color: rgba(26, 26, 26, 0.95);
  border-radius: 20rpx;
  padding: 16rpx 20rpx;
  margin: 20rpx 20rpx 20rpx;
  box-shadow: 0 8rpx 20rpx rgba(0, 0, 0, 0.3);
  position: relative;
  overflow: hidden;
  z-index: 1;
  backdrop-filter: blur(5px);
  border: 1px solid rgba(255, 255, 255, 0.1);

  /* 气泡容器 */
  .bubble-container {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    overflow: hidden;
    z-index: -1;
  }

  /* 通用气泡样式 */
  .bubble {
    position: absolute;
    border-radius: 50%;
    opacity: 0;
    transform: translateY(100%);
    animation-timing-function: cubic-bezier(0.25, 0.1, 0.25, 1);
    animation-iteration-count: infinite;
    background: radial-gradient(circle at 30% 30%,
      rgba(255, 255, 255, 0.8) 5%,
      rgba(255, 255, 255, 0.3) 10%,
      rgba(173, 216, 230, 0.3) 30%,
      rgba(173, 216, 230, 0.1) 80%);
    backdrop-filter: blur(1px);
    box-shadow: 0 0 10rpx rgba(255, 255, 255, 0.5),
                inset 0 0 15rpx rgba(255, 255, 255, 0.8),
                inset 5rpx 5rpx 12rpx rgba(255, 255, 255, 0.5);
    border: 1rpx solid rgba(255, 255, 255, 0.4);
  }

  /* 气泡大小、位置和动画定义 */
  .bubble-1 {
    width: 40rpx;
    height: 40rpx;
    left: 15%;
    animation: bubble-float 8s infinite;
    animation-delay: 0.2s;
  }

  .bubble-2 {
    width: 25rpx;
    height: 25rpx;
    left: 35%;
    animation: bubble-float 10s infinite;
    animation-delay: 1s;
  }

  .bubble-3 {
    width: 50rpx;
    height: 50rpx;
    left: 55%;
    animation: bubble-float 7s infinite;
    animation-delay: 0.5s;
  }

  .bubble-4 {
    width: 20rpx;
    height: 20rpx;
    left: 75%;
    animation: bubble-float 11s infinite;
    animation-delay: 1.5s;
  }

  .bubble-5 {
    width: 35rpx;
    height: 35rpx;
    left: 85%;
    animation: bubble-float 9s infinite;
    animation-delay: 0.7s;
  }

  .bubble-6 {
    width: 30rpx;
    height: 30rpx;
    left: 25%;
    animation: bubble-float 12s infinite;
    animation-delay: 2s;
  }

  @keyframes bubble-float {
    0% {
      transform: translateY(120%) translateX(0) scale(0.3);
      opacity: 0;
    }
    10% {
      opacity: 0.8;
      transform: translateY(100%) translateX(5rpx) scale(0.5);
    }
    30% {
      transform: translateY(50%) translateX(-10rpx) scale(0.8);
      opacity: 0.7;
    }
    50% {
      transform: translateY(0%) translateX(5rpx) scale(1);
      opacity: 0.6;
    }
    70% {
      transform: translateY(-50%) translateX(-10rpx) scale(0.9);
      opacity: 0.5;
    }
    90% {
      opacity: 0.4;
      transform: translateY(-100%) translateX(10rpx) scale(0.7);
    }
    100% {
      transform: translateY(-120%) translateX(0) scale(0.5);
      opacity: 0;
    }
  }

  .card-main {
    display: flex;
    align-items: flex-start;
    justify-content: space-between;
    position: relative;
    z-index: 2;

    .user-basic-info {
      flex: 1;
      display: flex;
      align-items: flex-start;

      .user-avatar {
        width: 80rpx;
        height: 80rpx;
        border-radius: 50%;
        margin-right: 15rpx;
        border: 3rpx solid rgba(255, 255, 255, 0.3);
        box-shadow: 0 0 10rpx rgba(255, 255, 255, 0.2);
        transition: transform 0.3s ease;

        &:active {
          transform: scale(0.95);
        }
      }

      .user-name-info {
        flex: 1;

        .user-name-wrapper {
          display: flex;
          align-items: center;

          .user-nickname {
            font-size: 28rpx;
            font-weight: bold;
            color: #ffffff;
            margin-bottom: 6rpx;
            text-shadow: 0 0 5rpx rgba(255, 255, 255, 0.3);
          }

          .vip-icon {
            width: 30rpx;
            height: 30rpx;
            margin-left: 6rpx;
          }
        }

        .user-tags {
          display: flex;
          flex-wrap: wrap;

          .tag {
            font-size: 20rpx;
            padding: 2rpx 12rpx;
            border-radius: 14rpx;
            margin-right: 8rpx;
            color: #fff;
            background: linear-gradient(135deg, rgba(255, 255, 255, 0.2), rgba(255, 255, 255, 0));
            backdrop-filter: blur(3px);
            border: 1px solid rgba(255, 255, 255, 0.1);
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
            transition: transform 0.2s ease;

            &.age {
              background-color: rgba(255, 71, 87, 0.7);
            }

            &.gender {
              background-color: rgba(84, 109, 229, 0.7);
            }

            &.location {
              background-color: rgba(46, 213, 115, 0.7);
            }
          }
        }

        .user-signature {
          margin-top: 8rpx;
          font-size: 24rpx;
          color: rgba(255, 255, 255, 0.8);
          line-height: 1.3;
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          line-clamp: 2;
          -webkit-box-orient: vertical;
          font-style: italic;
        }
      }
    }

    .user-albums-preview {
      display: flex;
      align-items: center;
      margin-left: 10rpx;

      .album-preview-image {
        width: 70rpx;
        height: 70rpx;
        border-radius: 8rpx;
        margin-left: 6rpx;
        flex-shrink: 0;
        border: 2rpx solid rgba(255, 255, 255, 0.3);
        box-shadow: 0 3rpx 8rpx rgba(0, 0, 0, 0.2);
        transition: transform 0.2s ease;

        &:active {
          transform: scale(0.95);
        }
      }

      .album-more {
        width: 70rpx;
        height: 70rpx;
        border-radius: 8rpx;
        background: linear-gradient(145deg, rgba(255, 255, 255, 0.2), rgba(255, 255, 255, 0.05));
        display: flex;
        align-items: center;
        justify-content: center;
        text-align: center;
        color: #fff;
        font-size: 20rpx;
        margin-left: 6rpx;
        border: 1px solid rgba(255, 255, 255, 0.1);
        box-shadow: 0 3rpx 8rpx rgba(0, 0, 0, 0.2);
      }
    }
  }

  .interest-scroll {
    margin-top: 10rpx;
    margin-bottom: 0;
    height: 50rpx;
    white-space: nowrap;
    position: relative;
    z-index: 2;
  }

  .interest-tags {
    display: inline-flex;
    padding: 4rpx 0;

    .interest-tag {
      font-size: 22rpx;
      background: linear-gradient(135deg, rgba(255, 255, 255, 0.15), rgba(255, 255, 255, 0.05));
      color: #fff;
      padding: 4rpx 16rpx;
      border-radius: 20rpx;
      margin-right: 10rpx;
      display: inline-block;
      backdrop-filter: blur(2px);
      border: 1px solid rgba(255, 255, 255, 0.1);
      box-shadow: 0 2rpx 5rpx rgba(0, 0, 0, 0.2);
      transition: transform 0.2s ease, background-color 0.2s ease;

      &:active {
        transform: scale(0.95);
        background-color: rgba(255, 255, 255, 0.2);
      }
    }
  }
}



/* VIP卡片特效样式 */
.vip-card {
  background: linear-gradient(135deg, rgba(20, 20, 20, 0.95), rgba(40, 30, 10, 0.95));
  border: 1px solid rgba(255, 215, 0, 0.3);
  box-shadow: 0 8rpx 25rpx rgba(255, 215, 0, 0.2);
}

/* VIP特效容器 */
.vip-effects {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  overflow: hidden;
  z-index: -1;
}

/* VIP光晕效果 */
.vip-glow {
  position: absolute;
  width: 100%;
  height: 100%;
  background: radial-gradient(ellipse at center,
    rgba(255, 215, 0, 0.1) 0%,
    rgba(255, 215, 0, 0.05) 30%,
    rgba(255, 215, 0, 0) 70%);
  animation: glow-pulse 3s infinite alternate;
}

@keyframes glow-pulse {
  0% {
    opacity: 0.3;
  }
  100% {
    opacity: 0.8;
  }
}

/* 金色粒子效果 */
.gold-particle {
  position: absolute;
  background: radial-gradient(ellipse at center,
    rgba(255, 255, 255, 0.9) 0%,
    rgba(255, 223, 0, 0.8) 30%,
    rgba(255, 215, 0, 0.6) 60%,
    rgba(255, 215, 0, 0) 100%);
  border-radius: 50%;
  opacity: 0;
  box-shadow: 0 0 8rpx rgba(255, 215, 0, 0.6);
}

/* 为每个粒子设置不同的大小、位置和动画 */
.particle-1 {
  width: 8rpx;
  height: 8rpx;
  animation: particle-float 6s infinite;
  animation-delay: 0.1s;
}

.particle-2 {
  width: 6rpx;
  height: 6rpx;
  animation: particle-float 5s infinite;
  animation-delay: 1s;
}

.particle-3 {
  width: 12rpx;
  height: 12rpx;
  animation: particle-float 7s infinite;
  animation-delay: 0.5s;
}

.particle-4 {
  width: 5rpx;
  height: 5rpx;
  animation: particle-float 8s infinite;
  animation-delay: 0.8s;
}

.particle-5 {
  width: 10rpx;
  height: 10rpx;
  animation: particle-float 6.5s infinite;
  animation-delay: 0.3s;
}

.particle-6 {
  width: 7rpx;
  height: 7rpx;
  animation: particle-float 7.5s infinite;
  animation-delay: 1.2s;
}

.particle-7 {
  width: 9rpx;
  height: 9rpx;
  animation: particle-float 5.5s infinite;
  animation-delay: 0.7s;
}

.particle-8 {
  width: 8rpx;
  height: 8rpx;
  animation: particle-float 6.8s infinite;
  animation-delay: 1.5s;
}

.particle-9 {
  width: 11rpx;
  height: 11rpx;
  animation: particle-float 7.2s infinite;
  animation-delay: 0.2s;
}

.particle-10 {
  width: 6rpx;
  height: 6rpx;
  animation: particle-float 5.8s infinite;
  animation-delay: 1.8s;
}

.particle-11 {
  width: 9rpx;
  height: 9rpx;
  animation: particle-float 6.3s infinite;
  animation-delay: 1s;
}

.particle-12 {
  width: 7rpx;
  height: 7rpx;
  animation: particle-float 7.8s infinite;
  animation-delay: 0.4s;
}

/* 随机漂浮路径 */
@keyframes particle-float {
  0% {
    transform: translate(0, 0) scale(0);
    opacity: 0;
  }
  10% {
    opacity: 0.8;
    transform: translate(20rpx, -20rpx) scale(1);
  }
  30% {
    transform: translate(-20rpx, -40rpx) scale(0.9);
  }
  50% {
    transform: translate(30rpx, -60rpx) scale(1);
    opacity: 0.8;
  }
  70% {
    transform: translate(-30rpx, -80rpx) scale(0.8);
    opacity: 0.6;
  }
  90% {
    opacity: 0.4;
    transform: translate(10rpx, -100rpx) scale(0.7);
  }
  100% {
    transform: translate(0, -120rpx) scale(0);
    opacity: 0;
  }
}

/* 设置粒子的初始位置 */
.particle-1 { top: 20%; left: 10%; }
.particle-2 { top: 75%; left: 80%; }
.particle-3 { top: 40%; left: 30%; }
.particle-4 { top: 60%; left: 70%; }
.particle-5 { top: 30%; left: 85%; }
.particle-6 { top: 80%; left: 25%; }
.particle-7 { top: 50%; left: 90%; }
.particle-8 { top: 15%; left: 60%; }
.particle-9 { top: 90%; left: 40%; }
.particle-10 { top: 10%; left: 30%; }
.particle-11 { top: 65%; left: 15%; }
.particle-12 { top: 35%; left: 50%; }

/* VIP标签特效 */
.vip-tag {
  background: linear-gradient(135deg, #ffd700, #ffb700) !important;
  color: #333 !important;
  border: 1px solid rgba(255, 215, 0, 0.6) !important;
  box-shadow: 0 3rpx 8rpx rgba(255, 215, 0, 0.3) !important;
  animation: tag-shine 2s infinite alternate;
}

@keyframes tag-shine {
  0% {
    box-shadow: 0 3rpx 8rpx rgba(255, 215, 0, 0.3);
  }
  100% {
    box-shadow: 0 3rpx 10rpx rgba(255, 215, 0, 0.6);
  }
}
</style>
